#!/bin/bash

# 1. 创建目录并初始化为git仓库
if [ ! -d "/app/LIUJUEmyz" ]; then
  mkdir -p /app/LIUJUEmyz
  cd /app/LIUJUEmyz
  git init
else
  cd /app/LIUJUEmyz
fi

# 2. 创建/app/node/app目录
mkdir -p /app/node/app

# 3. 克隆项目
if [ ! -d "liujuemyz" ]; then
  git clone https://gitee.com/ma-yi_zhao/liujuemyz.git
fi

# 4. 复制内容到/app/node/app目录
cp -r liujuemyz/* /app/node/app

# 5. 切换npm镜像源
docker exec -i node sh -c "npm config set registry http://registry.npm.taobao.org/"

# 6. 进入node容器并执行命令
docker exec -i node bash <<'EOF'

# 7. 切换到app目录并下载依赖
cd /app
if [ ! -d "node_modules" ]; then
  npm i
fi

# 8. 启动项目
if ! pgrep -f "npm run dev" > /dev/null; then
  nohup npm run dev &
fi

# 退出容器
exit
EOF

# 9. 写入nginx配置
nginx_conf="/app/nginx/default.conf"
if ! grep -q "listen       81;" "$nginx_conf"; then
  cat > "$nginx_conf" <<'EOF'
server {
    listen       81;
    listen  [::]:81;
    server_name  localhost;

    location / {
        proxy_pass http://192.168.5.105:8080/;
        proxy_set_header Host $host:$server_port;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
EOF
fi

# 10. 重启nginx
docker restart nginx

# 11. 检查容器运行状态
docker ps -a

# 12. 关闭防火墙
systemctl stop firewalld

